package com.zcxy.fast.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxy.fast.bean.PageQuery;
import com.zcxy.fast.constant.CommonConstant;
import com.zcxy.fast.entity.SysAttachment;
import com.zcxy.fast.mapper.SysAttachmentMapper;
import com.zcxy.fast.mybatisExtend.BaseServiceImpl;
import com.zcxy.fast.service.ISysAttachmentService;
import com.zcxy.fast.utils.BeanCopyUtil;
import com.zcxy.fast.utils.FileUtil;
import com.zcxy.fast.vo.SysAttachmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Service业务层处理
 *
 * @author zcc
 * @email 860474958@qq.com
 * @date 2020-07-01
 */
@Service
@Slf4j
public class SysAttachmentServiceImpl extends BaseServiceImpl<SysAttachmentMapper, SysAttachment>
        implements ISysAttachmentService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<SysAttachmentVo> queryPageList(PageQuery<SysAttachment> queryVo) {
        QueryWrapper queryWrapper = new QueryWrapper(queryVo.getT() == null ? new SysAttachment() : queryVo.getT());
        Page page = new Page(queryVo.getPageNo(), queryVo.getPageSize());
        IPage<SysAttachment> sysUserVoIPage = baseMapper.selectPage(page, queryWrapper);
        return BeanCopyUtil.copyPage(sysUserVoIPage, SysAttachmentVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysAttachmentVo> queryList(SysAttachment queryVo) {

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysAttachment(SysAttachment queryVo) {
        queryVo.setDelFlag(CommonConstant.DEL_FLAG_1);
        //TODO 具体新增业务限制各自实现
        baseMapper.insert(queryVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysAttachment(SysAttachment queryVo) {
        //查询数据库的实体(主键校验在controller的校验器里面)
        SysAttachment sysAttachmentDb = baseMapper.selectById(queryVo.getId());
        BeanCopyUtil.copyObject(queryVo, sysAttachmentDb);
        baseMapper.updateById(sysAttachmentDb);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeSysAttachment(String id) {
        baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAllSysAttachment(List<String> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", ids);
        baseMapper.delete(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void download(SysAttachment queryVo, HttpServletResponse response) throws IOException {
        List<SysAttachment> sysAttachments = baseMapper.selectList(new QueryWrapper<>(queryVo));
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysAttachment sysAttachmentExcel : sysAttachments) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("", sysAttachmentExcel.getId());
            map.put("对应业务的uuid", sysAttachmentExcel.getFileUuid());
            map.put("附件名称", sysAttachmentExcel.getFileName());
            map.put("文件oss外网url", sysAttachmentExcel.getFileOssUrl());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    @Override
    public void updateOrAddSysAttachments(String bussinessId, List<SysAttachment> sysAttachments) {
        LambdaQueryWrapper<SysAttachment> query = new LambdaQueryWrapper<>();
        query.eq(SysAttachment::getFileUuid, bussinessId);
        query.eq(SysAttachment::getDelFlag, CommonConstant.DEL_FLAG_1);
        List<SysAttachment> list = list(query);
        //数据库已存在的文件
        Map<String, SysAttachment> db = new HashMap<>();
        //需要更新的数据文件
        Map<String, SysAttachment> update = new HashMap<>();
        if (CollectionUtil.isNotEmpty(list)) {
            db = list.stream().collect(Collectors.toMap(SysAttachment::getFileName, Function.identity()));
        }
        if (CollectionUtil.isNotEmpty(sysAttachments)) {
            update = sysAttachments.stream().collect(Collectors.toMap(SysAttachment::getFileName, Function.identity()));
        }
        final Map<String, SysAttachment> dbMap = db;
        final Map<String, SysAttachment> updateMap = update;
        List<SysAttachment> addList = new ArrayList<>();
        List<SysAttachment> delList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sysAttachments)) {
            sysAttachments.forEach(i -> {
                if (dbMap.get(i.getFileName()) == null) {
                    i.setId("");
                    addList.add(i);
                }
            });
        }
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(i -> {
                if (updateMap.get(i.getFileName()) == null) {
                    delList.add(i);
                }
            });
        }
        if (CollectionUtil.isNotEmpty(addList))
            saveOrUpdateBatch(addList);
        if(CollectionUtil.isNotEmpty(delList)){
            List<String> ids=delList.stream().map(SysAttachment::getId).collect(Collectors.toList());
            baseMapper.deleteBatchIds(ids);
        }
    }


}
